package com.heima.app.gateway.filter;

import com.heima.app.gateway.pojo.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器
 */
@Component
public class AuthorFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.判断是否是登录需求
        if(request.getURI().getPath().contains("/login")){
        //2.如果是，则放行
            return chain.filter(exchange);
        }

        //3.如果不是，则检验token
        String token = request.getHeaders().getFirst("token");

        if(StringUtils.isBlank(token)){
        //4.如果token为空，则返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.如果不为空，则检验token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1 || i==2){
        //6.如果无效，则返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //7，如果有效，则放行
        return chain.filter(exchange);
    }

    /**
     *  过滤器的执行优先级，值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
